﻿using System;
using System.Linq;
using System.Xml;

namespace Web.FrontEnd.Config
{
    public class Configuration : Tmkilla.Localizr.Web.Base.Config.Configuration
    {
        #region Attributes

        public static bool Installed { get; set; }

        #endregion

        #region Public methods

        public new static void Init()
        {
            Tmkilla.Localizr.Web.Base.Config.Configuration.Init();
            ReadLocalConfiguration();
        }

        #endregion

        #region Private methods 

        private static void ReadLocalConfiguration()
        {
            // Check for subfolder existance
            if (!System.IO.Directory.Exists(System.IO.Path.Combine(AppSettingsFolder, "Web.FrontEnd")))
                System.IO.Directory.CreateDirectory(System.IO.Path.Combine(AppSettingsFolder, "Web.FrontEnd"));

            // Check for configuration file existance
            var filename = System.IO.Path.Combine(AppSettingsFolder, "Web.FrontEnd", "localconfiguration.xml");
            if (!System.IO.File.Exists(filename)) CreateBasicLocalConfigurationFile(filename);

            // Read and parse configuration file
            XmlNode node;
            var xmlDoc = new XmlDocument();
            xmlDoc.Load(filename);
            var rootNode = xmlDoc.DocumentElement;

            // Read settings
            Installed = (node = rootNode.SelectSingleNode("installed")) != null ? node.InnerText == "1" : false;
        }

        private static void CreateBasicLocalConfigurationFile(string filename)
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));

            var rootNode = xmlDoc.CreateElement("configuration");
            xmlDoc.AppendChild(rootNode);

            var node = xmlDoc.CreateElement("installed");
            node.InnerText = "0";
            rootNode.AppendChild(node);

            xmlDoc.Save(filename);
        }

        #endregion
    }
}